var heartbeat_timer = 0;
var last_health = -1;
var health_timeout = 3000;
var sgpassword = localStorage.getItem("password");
var ip = localStorage.getItem("ip");
var wsisopen = 0;

$(document).ready(function() {
	$('.modal').modal({
		dismissible: false
	});
	$('input.autocomplete').autocomplete({
		data: {
			"stop": null,
			"op": null,
			"deop": null,
			"whitelist add": null,
			"whitelist remove": null,
			"ban": null,
			"unban": null,
			"say": null,
			"help": null,
			"msg": null,
			"kill": null

		}
	});
	$('select').material_select();
	$(".button-collapse").sideNav();

	$("#ip").attr("value", ip);
	if(!localStorage.ip.replace(/(^\s*)|(\s*$)/g, "")) {
		ip = "127.0.0.1";
		window.localStorage.setItem("ip", "127.0.0.1");
		$('#firstuse').modal('open');
	}
	$(".modal-password").click(function() {
		var password = $("#password").val();
		window.localStorage.setItem("password", password);
		$('#needpassword').modal('close');
		location.reload(true);
	});

	setInterval(function() {
		keepstatus()
	}, 1000);
})
$(".modal-ip").click(function() {
	var ip = $("#ip").val();
	window.localStorage.setItem("ip", ip.replace(/(^\s*)|(\s*$)/g, ""));
	$('#firstuse').modal('close');
	location.reload(true);
});

$(".edit-ip").click(function() {
	$('#firstuse').modal('open');
});
$(".logout").click(function() {
	window.localStorage.clear();
	Materialize.toast('已经清空浏览器用户数据', 2000, '', function() {
		location.reload(true)
	})
	$('#firstuse').modal('close');
});
$(function() {
	ws = ws_conn("ws://" + ip + ":23333");
});

function keepalive(ws) {
	var time = new Date();
	if(last_health != -1 && (time.getTime() - last_health > health_timeout)) {
		//此时即可以认为连接断开，可是设置重连或者关闭
		$("#keeplive_box").html("通讯异常");
		wsisopen = 0;
		errorbgc();

		//ws.close();
	} else {
		$("#keeplive_box").html("通讯正常");
		wsisopen = 1;
		okbgc();
		if(ws.bufferedAmount == 0) {
			ws.send('HeartBeat' + sgpassword);
		}
	}
}

//websocket function
function ws_conn(to_url) {
	to_url = to_url || "";
	if(to_url == "") {
		return false;
	}

	clearInterval(heartbeat_timer);
	var ws = new WebSocket(to_url);
	ws.onopen = function() {
		$("#statustxt").html("connected.");
		$("#send_btn").attr("disabled", false);
		heartbeat_timer = setInterval(function() {
			keepalive(ws)
		}, 1000);
	}
	ws.onerror = function() {
		clearInterval(heartbeat_timer);
		$("#keeplive_box").html("通讯异常");
		$('#firstuse').modal('open');
		wsisopen = 0;
		errorbgc();
	}
	ws.onclose = function() {
		clearInterval(heartbeat_timer);
		$("#keeplive_box").html("通讯异常");
		wsisopen = 0;
		errorbgc();
	}

	ws.onmessage = function(msg) {
		var time = new Date();
		if(msg.data == "need password") {
			$('#needpassword').modal('open');
		}
		if(msg.data == ('HeartBeat')) {
			last_health = time.getTime();
			return;
		}
		var thejson = strToJson(msg.data);
		if(thejson.type == "status") {
			$(".cpu").text(thejson.cpu);
			$(".memory").text(thejson.memory);
			$(".vmemory").text(thejson.vmemory);
			return;
		}
		if(thejson.type == "servercfg") {
			viewservercfg(thejson);
			return;
		}
		msgjudge(msg.data);

	}

	return ws;
}

function msgjudge(inmsg) {
	console.log(inmsg);
	/*if(){
		
	}*/
}

function errorbgc() { //连接错误时
	$(".grey,.light-blue").addClass("red");
	$(".grey,.light-blue").removeClass("grey");
	$(".grey,.light-blue").removeClass("lighten-4");
	$(".grey,.light-blue").removeClass("light-blue");
	$(".cpu").text("null");
	$(".memory").text("null");
	$(".vmemory").text("null");
}

function okbgc() { //连接正常时
	$(".grey,.red").addClass("light-blue");
	$(".grey,.light-blue").removeClass("grey");
	$(".grey,.red").addClass("lighten-4");
	$(".grey,.red").removeClass("red");
}

function keepstatus() {
	ws.send('getstatus' + sgpassword);
}

function strToJson(str) {
	return JSON.parse(str);
}

function viewservercfg(cfgjson) {
	$("#nether").attr('checked', cfgjson.nether === "true");
	$("#fly").attr('checked', cfgjson.fly === "true");
	$("#npc").attr('checked', cfgjson.npc === "true");
	$("#whitelist").attr('checked', cfgjson.whitelist === "true");
	$("#animals").attr('checked', cfgjson.animals === "true");
	$("#hardcore").attr('checked', cfgjson.hardcore === "true");
	$("#onlinemode").attr('checked', cfgjson.onlinemode === "true");
	$("#pvp").attr('checked', cfgjson.pvp === "true");
	$("#monster").attr('checked', cfgjson.monster === "true");
	$("#commandblock").attr('checked', cfgjson.commandblock === "true");
	$("#serverpost").val(cfgjson.post);
	$("#maxheight").val(cfgjson.maxheight);
	$("#maxplayers").val(cfgjson.maxplayers);
	$("#motd").val(decodeUnicode(cfgjson.motd));
	$("#difficulty").find("option[value='" + cfgjson.difficulty + "']").attr("selected", true);
	$('select').material_select('destroy');
	$('select').material_select();
	$("#gamemode").find("option[value='" + cfgjson.gamemode + "']").attr("selected", true);
	$('select').material_select('destroy');
	$('select').material_select();
	Materialize.updateTextFields();
}

$(".save_servercfg").click(function() {
	var cfgjson = {};
	cfgjson.password = sgpassword;
	cfgjson.nether = $("#nether").prop("checked").toString();
	cfgjson.fly = $("#fly").prop("checked").toString();
	cfgjson.npc = $("#npc").prop("checked").toString();
	cfgjson.whitelist = $("#whitelist").prop("checked").toString();
	cfgjson.animals = $("#animals").prop("checked").toString();
	cfgjson.hardcore = $("#hardcore").prop("checked").toString();
	cfgjson.onlinemode = $("#onlinemode").prop("checked").toString();
	cfgjson.monster = $("#monster").prop("checked").toString();
	cfgjson.pvp = $("#pvp").prop("checked").toString();
	cfgjson.commandblock = $("#commandblock").prop("checked").toString();
	
	cfgjson.post = $("#serverpost").val();
	cfgjson.maxheight = $("#maxheight").val();
	cfgjson.maxplayers = $("#maxplayers").val();
	cfgjson.gamemode = $('#gamemode').val();
	cfgjson.difficulty = $('#difficulty').val();
	cfgjson.motd = encodeUnicode($("#motd").val());
	
	var cfgstr = "setservercfg" + JSON.stringify(cfgjson);
	console.log(cfgstr)
});

$("[data-tooltip='设置']").click(function() {
	ws.send("getservercfg" + sgpassword);
});

function encodeUnicode(str) {
	if (str == ""){return ""}
	var res = [];
	for(var i = 0; i < str.length; i++) {
		res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
	}
	return "\\u" + res.join("\\u");
}

function decodeUnicode(str) {
	str = str.replace(/\\/g, "%");
	return unescape(str);
}